package com.zengqingfa.juc.n4;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zengqingfa
 * @className Test8
 * @description
 * @create 2021/6/11 23:35
 */
@Slf4j(topic = "c.Test8")
public class Test8 {

    private static Integer i = 0;

    //如果使用monitor，线程安全
    private static Integer monitor = 0;

    public static void main(String[] args) throws InterruptedException {
        List<Thread> list = new ArrayList<>();
        for (int j = 0; j < 2; j++) {
            Thread thread = new Thread(() -> {
                for (int k = 0; k < 5000; k++) {
                    //线程不安全,不同的锁对象，引用不变，但是值变化
                    synchronized (i) {
                        i++;
                    }
                }
            }, "" + j);
            list.add(thread);
        }
        list.stream().forEach(t -> t.start());
        list.stream().forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        log.debug("{}", i);
    }
}